package com.zefor.warns;

import com.zefor.utils.CacheUtil;
import kd.bos.cache.LocalMemoryCache;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.earlywarn.EarlyWarnContext;
import kd.bos.entity.earlywarn.warn.plugin.IEarlyWarnCustomReceiver;
import kd.bos.kdtx.common.exception.KdtxException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.util.StringUtils;
import kd.drp.mdr.common.util.ObjectUtil;
import org.apache.cxf.Bus;

import java.util.*;


/*
 * 更新
 * */
public class EnvEmployeeWarnReceiverPlugin implements IEarlyWarnCustomReceiver {
    //获取缓存操作
    private final LocalMemoryCache localCache = CacheUtil.getCache();

    @Override
    public List<Long> getReceiverIds(EarlyWarnContext earlyWarnContext, DynamicObject[] dynamicObjects) {
        // 需要通知的人的id
        List<Long> receiverIds = new ArrayList<>();
        // 获取需要通知的内容
        DynamicObjectCollection warnDataList = earlyWarnContext.getWarnDataList();
        // 获取到需要通知的人
        DynamicObject[] warnStandard = BusinessDataServiceHelper.load(
                "n716_warnstandard",
                "n716_mulilangtextfield,n716_decimalfield, n716_decimalfield1, n716_checkboxfield, n716_checkboxfield1,n716_combofield",
                new QFilter("n716_combofield", QCP.in, new ArrayList<String>() {{
                    add("温度");
                    add("湿度");
                    add("二氧化碳");
                    add("光照量");
                }}).toArray());
        if (ObjectUtil.isEmpty(warnDataList)) {
            throw new KdtxException("未获取到预警标准信息");
        }
        //将预警标准对象转换为map
        Map<String, Boolean[]> envWarnStandard = transitionArrOfObj(warnStandard);
        for (DynamicObject envWarn : warnDataList) {
            //因为这个方法会执行两次,当预警消息为空的时候停止记录
            if (ObjectUtil.isEmpty(localCache.get(envWarn.getPkValue() + "warnMses"))) break;
            HashSet<String> warnMses = (HashSet<String>) localCache.get(envWarn.getPkValue() + "warnMses");
            localCache.remove(envWarn.getPkValue() + "warnMses");

            //获取栏舍信息
            DynamicObject corralInfo = queryPicByFormName("n716_corral", (Long) envWarn.getDynamicObject("n716_basedatafield1").getPkValue());
            //获取养殖场信息
            DynamicObject farmInfo = queryPicByFormName("n716_farm", (Long) envWarn.getDynamicObject("n716_basedatafield").getPkValue());
            //保存信息
            DynamicObject warnLog = BusinessDataServiceHelper.newDynamicObject("n716_warn_log");
            for (String warnMsg : warnMses) {
                //获取预警类型
                String warnType = getWarnTypeByWarnInfo(warnStandard, warnMsg);
                if (StringUtils.isEmpty(warnType)) throw new KdtxException("未获取到正确的预警类型");

                //获取勾选的负责人
                boolean flag1 = envWarnStandard.get(warnType)[0];
                boolean flag2 = envWarnStandard.get(warnType)[1];
                //需要通知栏舍负责人
                if (flag1) {
                    //获取到栏舍信息
                    DynamicObject corral = envWarn.getDynamicObject("n716_basedatafield1");
                    Long pic = (Long) queryPicByFormName("n716_corral", (Long) corral.getPkValue())
                            .getDynamicObject("n716_userfield")
                            .getPkValue();
                    // 添加到预警对象
                    receiverIds.add(pic);
                }

                if (flag2) {
                    //获取养殖场信息
                    DynamicObject farm = envWarn.getDynamicObject("n716_basedatafield");
                    Long pic = (Long) queryPicByFormName("n716_farm", (Long) farm.getPkValue())
                            .getDynamicObject("n716_userfield")
                            .getPkValue();
                    receiverIds.add(pic);
                }
                //名称
                warnLog.set("n716_textfield", corralInfo.getString("name") + warnMsg);
                //设置养殖场信息
                warnLog.set("n716_basedatafield", queryPicByFormName("n716_farm", (Long) envWarn.getDynamicObject("n716_basedatafield").getPkValue()));
                //设置栏舍
                warnLog.set("n716_basedatafield1", corralInfo);
                // 设置设备信息
                DynamicObject[] equipment = BusinessDataServiceHelper
                        .load(
                                "n716_dev_manager",
                                "n716_basedatafield",
                                new QFilter[]{
                                        new QFilter("n716_basedatafield1", QCP.equals, corralInfo.getPkValue())
                                });
                for (DynamicObject dynamicObject : equipment) {
                    //环境信息
                    if(dynamicObject.getDynamicObject("n716_basedatafield").getString("name").contains("环境")){
                        warnLog.set("n716_basedatafield2", dynamicObject.getDynamicObject("n716_basedatafield"));
                        break;
                    }
                }
                //设置单据状态
                warnLog.set("billstatus", "A");
                //设置预警状态
                warnLog.set("n716_combofield", "待解决");
                //设置预警类型
                warnLog.set("n716_combofield1", warnType + "预警");
                //设置负责人
                if (flag1 && flag2)
                    warnLog.set("n716_textfield1", corralInfo.getDynamicObject("n716_userfield").getString("name") + "," + farmInfo.getDynamicObject("n716_userfield").getString("name"));
                else if (flag2)
                    warnLog.set("n716_textfield1", farmInfo.getDynamicObject("n716_userfield").getString("name"));
                else
                    warnLog.set("n716_textfield1", corralInfo.getDynamicObject("n716_userfield").getString("name"));
                //保存记录
                SaveServiceHelper.saveOperate("n716_warn_log", new DynamicObject[]{warnLog}, OperateOption.create());
            }
        }
        return receiverIds;

    }

    /*
     * 通过表单名称和id查询基础资料
     * @param 单据名称
     * @param 单据id
     * @return 完整单据信息
     * */
    private DynamicObject queryPicByFormName(String formName, Long id) {
        DynamicObject[] load = BusinessDataServiceHelper.load(formName, "name,n716_userfield", new QFilter("id", QCP.equals, id).toArray());
        return load[0];
    }

    /*
     * 实体类数组转换为map对象
     * @param 实体类数据
     * @return map结果数据包含类名,boolean第一个值为是否需要通知栏舍负责人,第二个值为是否需要通知养殖场负责人
     * */
    private Map<String, Boolean[]> transitionArrOfObj(DynamicObject[] warnStandard) {
        HashMap<String, Boolean[]> map = new HashMap<>();
        for (DynamicObject dynamicObject : warnStandard) {
            String key = dynamicObject.getString("n716_combofield");
            Boolean[] val = {dynamicObject.getBoolean("n716_checkboxfield"), dynamicObject.getBoolean("n716_checkboxfield1")};
            map.put(key, val);
        }
        return map;
    }


    /*
     * 将预警信息中的预警类型提取
     * @param 预警类型标准
     * @param 预警字段
     * @return 提取出的预警信息
     * */
    private String getWarnTypeByWarnInfo(DynamicObject[] warnStandard, String warnMsg) {
        for (DynamicObject dynamicObject : warnStandard) {
            if (warnMsg.contains(dynamicObject.getString("n716_combofield"))) {
                return dynamicObject.getString("n716_combofield");
            }
        }
        return null;
    }
}
